<template>
  <div>
    <van-button
      style="position: fixed; top: 30px; right: 0; z-index: 999"
      type="primary"
      >loading:{{ loading }}===finished:{{ finished }}===refreshing:{{
        refreshing
      }}===={{ list.length }}</van-button
    >
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="到底了宝子"
        @load="onLoad"
        offset="100"
      >
        <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="index + '------' + item.goods_name"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      pagesize: 20,
      pagenum: 1,
      refreshing: false
    };
  },
  created () {
    // this.getData()
  },
  methods: {
    onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1);
      //   }

      //   // 加载状态结束
      //   this.loading = false;

      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true;
      //   }
      // }, 1000);
      setTimeout(() => {
        if (this.pagenum > 3) {
          this.loading = false;//加载最后一次要把loading 状态变成false
          this.finished = true;
          return
        }
        this.getData()
        this.pagenum += 1
      }, 1000)

    },
    async getData () {
      const res = await axios({
        url: 'http://vue-shop-api-t.itheima.net/api/private/v1/goods',
        params: {
          pagenum: this.pagenum,
          pagesize: this.pagesize
        },
        headers: {
          Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE2ODU0NDk2ODcsImV4cCI6MTY4NTUzNjA4N30.SlazcyT89ShD4qPHfBN_SB-sF5v-XTC7k-fWQoqnmVU'
        }
      })
      console.log(res)
      this.list = this.refreshing ? res.data.data.goods : [...this.list, ...res.data.data.goods]
      //  异步写在 onload里面会直接全部加载
      this.loading = false;
      this.refreshing = false
    },
    onRefresh () {
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      // this.loading = true;
      this.pagenum = 1
      this.onLoad();
    },
  },
};
</script>
<style lang='less'  scoped>
</style>
